package team.pwy.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayResponse;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import team.pwy.config.AlipayVipConfig;
import team.pwy.mapper.MemberMapper;
import team.pwy.pojo.entity.VipOrder;
import team.pwy.service.SnowFlake;
import team.pwy.service.VipOrderService;

import java.io.UnsupportedEncodingException;


@Controller
@RequestMapping("alipay")
public class AlipayVipController {

    @Autowired
    private VipOrderService vipOrderService;

    @Autowired
    private MemberMapper memberMapper;

    @GetMapping("/payVip")
    @ResponseBody
    public String pay(Integer userId,Integer secId,String price,HttpServletRequest request) {
        AlipayClient alipayClient =  new DefaultAlipayClient(AlipayVipConfig.gatewayUrl, AlipayVipConfig.app_id, AlipayVipConfig.merchant_private_key, "json", AlipayVipConfig.charset, AlipayVipConfig.alipay_public_key, AlipayVipConfig.sign_type);
        AlipayTradePagePayRequest alipayRequest =  new  AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayVipConfig.return_url );
        alipayRequest.setNotifyUrl(AlipayVipConfig.notify_url);
        String timeout_express = "1c";
        String body="";
        SnowFlake snowFlake1 = new SnowFlake(2,5);
        String out_trade_no = String.valueOf(snowFlake1.nextId());
        String total_amount = price;
        String subject = "票无忧影城会员";
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String payResult = null;
        try {
            AlipayResponse alipayResponse =  alipayClient.pageExecute(alipayRequest);

            System.out.println("pay code:"+ alipayResponse.getCode());
            System.out.println("pay getSubCode:"+ alipayResponse.getSubCode());
            System.out.println("pay getMsg:"+ alipayResponse.getMsg());
            System.out.println("pay isSuccess:"+ alipayResponse.isSuccess());
            payResult =  alipayResponse.getBody();// getBody() 支付后，支付宝返回的支付的信息
            System.out.println("支付宝返回的支付的信息：" + payResult);

        } catch (AlipayApiException e) {
            e.printStackTrace();
            System.out.println("6666"+e.getErrMsg());
        }
        vipOrderService.addOrder(userId,out_trade_no,total_amount,secId);

        return  payResult;
    }

//     支付后的 获得 支付宝的信息 payResult --->request
    @RequestMapping("alipayVipReturnNotice")
    public String alipayNotifyNotice(HttpServletRequest request) throws UnsupportedEncodingException {
        System.out.println("异步请求，支付成功后，支付宝的返回数据是：" + request);
        //商户订单号
        String orderNum = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        //支付宝交易号
        String tradeNo = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
        //付款金额
        String payPrice = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

        VipOrder vipOrder = vipOrderService.findByOrdNum(orderNum);

        vipOrderService.updateOrderSta(vipOrder.getUserId());

        if (vipOrder.getSecId()==0){
            memberMapper.addByUserId(vipOrder.getUserId());
        } else if (vipOrder.getSecId()==1) {
            memberMapper.updateByUserId(vipOrder.getUserId());
        }else {
            memberMapper.updateOpenStatus(vipOrder.getUserId());
        }

        System.out.println("return orderNum:" + orderNum);
        System.out.println("return tradeNo:" + tradeNo);
        System.out.println("return payPrice:" + payPrice);
        System.out.println("666666666666666666666666666666666666666");
        return  "success";
    }
}
